package com.software.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.software.base.ResultInfo;
import com.software.bean.AdminBean;
import com.software.dto.*;
import com.software.mapper.AdminMapper;
import com.software.service.AdminService;
import com.software.utils.AssertUtil;
import com.software.utils.Md5Util;
import com.software.utils.PhoneUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wyj
 * @since 2024-02-27
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, AdminBean> implements AdminService {


    @Autowired
    private AdminMapper adminMapper;


    /**
     * @description:获取管理员信息
     * @author: wyj
     * @date: 2024/4/9 19:16
     * @param:
     * @return:
     */
    @Override
    public AdminBean selectById(Integer id) {
        AssertUtil.isTrue(id == null || id == 0, "参数异常");
        AdminBean adminBean = adminMapper.selectById(id);
        AssertUtil.isTrue(adminBean == null, "返回值异常");
        return adminBean;
    }

    @Override
    public ResultInfo adminLogin(LoginDto loginDto, HttpServletRequest request) {
        AssertUtil.isTrue(StringUtils.isEmpty(loginDto.getAccount()), "参数异常");
        AssertUtil.isTrue(StringUtils.isEmpty(loginDto.getPassword()), "参数异常");
        AssertUtil.isTrue(StringUtils.isEmpty(loginDto.getCaptcha()), "参数异常");
        System.out.println(request.getSession().getAttribute("captcha"));
        AssertUtil.isTrue(!loginDto.getCaptcha().equals(request.getSession().getAttribute("captcha")), "验证码错误");
        AdminBean adminBean = adminMapper.selectByAccount(loginDto.getAccount());
        AssertUtil.isTrue(adminBean == null, "返回值异常");
        AssertUtil.isTrue(!adminBean.getAdminPassword().equals(Md5Util.encode(loginDto.getPassword())), "密码错误");
        AssertUtil.isTrue(adminBean.getAdminStatus() != 1, "账号异常");

        return ResultInfo.success(adminBean);
    }

    /**
     * @description:管理员更新头像
     * @author: wyj
     * @date: 2024/4/9 20:26
     * @param:
     * @return:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateAdminAvatar(AdminDto adminDto) {
        AssertUtil.isTrue(adminDto.getId() == null || adminDto.getId() == 0, "参数异常");
        AssertUtil.isTrue(adminDto.getFile() == null, "缺少头像图片");
        AdminBean adminBean = adminMapper.selectById(adminDto.getId());
        AssertUtil.isTrue(adminBean == null, "返回值异常");
        // 判断是否是默认头像 如果是默认头像就直接修改 不是默认头像就删除原本头像
        if (adminBean.getAdminFace().contains("default")) {
            adminBean.setAdminFace(saveImage(adminDto.getFile()));
            int update = adminMapper.updateById(adminBean);
            AssertUtil.isTrue(update != 1, "更新头像失败");
        } else {
            deleteImage(adminBean.getAdminFace());
            adminBean.setAdminFace(saveImage(adminDto.getFile()));
            int update = adminMapper.updateById(adminBean);
            AssertUtil.isTrue(update != 1, "更新头像失败");
        }
        return null;
    }

    /**
     * @description:管理员修改信息
     * @author: wyj
     * @date: 2024/4/9 21:15
     * @param:
     * @return:
     */
    @Override
    public Integer updateAdminInfo(UpdateAdminDto updateAdminDto) {
        AssertUtil.isTrue(updateAdminDto.getId() == null || updateAdminDto.getId() == 0, "参数异常");
        AssertUtil.isTrue(StringUtils.isEmpty(updateAdminDto.getAdminUsername()), "用户名不能为空");
        AssertUtil.isTrue(StringUtils.isEmpty(updateAdminDto.getAdminPhone()), "手机号不能为空");
        AssertUtil.isTrue(StringUtils.isEmpty(updateAdminDto.getAdminAccount()), "账号不能为空");
        AssertUtil.isTrue(PhoneUtils.isMobile(updateAdminDto.getAdminPhone()) == false, "手机号格式错误");
        AdminBean adminBean = adminMapper.selectById(updateAdminDto.getId());
        AssertUtil.isTrue(adminBean == null, "用户不存在");  // 判断是否存在该用户
        adminBean.setAdminAccount(updateAdminDto.getAdminAccount());
        adminBean.setAdminUsername(updateAdminDto.getAdminUsername());
        adminBean.setAdminPhone(updateAdminDto.getAdminPhone());
        int update = adminMapper.updateById(adminBean);
        return update == 1 ? 1 : 0;
    }

    /**
     * @description:更新管理员密码
     * @author: wyj
     * @date: 2024/4/9 21:54
     * @param:
     * @return:
     */
    @Override
    public Integer updatePassword(UpdateAdminPasswordDto updateAdminDto) {
        // 参数校验
        AssertUtil.isTrue(updateAdminDto.getId() == null || updateAdminDto.getId() == 0, "参数异常");
        AssertUtil.isTrue(StringUtils.isEmpty(updateAdminDto.getOldPassword()), "原密码不能为空");
        AssertUtil.isTrue(StringUtils.isEmpty(updateAdminDto.getNewPassword()), "新密码不能为空");
        AdminBean adminBean = adminMapper.selectById(updateAdminDto.getId());
        AssertUtil.isTrue(adminBean == null, "用户不存在");
        AssertUtil.isTrue(!adminBean.getAdminPassword().equals(Md5Util.encode(updateAdminDto.getOldPassword())), "原密码错误");
        adminBean.setAdminPassword(Md5Util.encode(updateAdminDto.getNewPassword()));
        int update = adminMapper.updateById(adminBean);
        return update == 1 ? 1 : 0;
    }

    /**
     * @description:获取管理员列表
     * @author: wyj
     * @date: 2024/4/16 20:30
     * @param:
     * @return:
     */
    @Override
    public List<AdminBean> getAdminList() {
        List<AdminBean> adminBeanList = adminMapper.getAdminList();
        AssertUtil.isTrue(adminBeanList.size() == 0, "获取管理员列表信息失败");
        return adminBeanList;
    }

    /**
     * @description:添加管理员
     * @author: wyj
     * @date: 2024/4/16 21:21
     * @param:
     * @return:
     */
    @Override
    public Integer addAdmin(AddAdminDto addAdminDto) {
        System.out.println(addAdminDto);
        AssertUtil.isTrue(StringUtils.isEmpty(addAdminDto.getAdminAccount()), "账号不能为空");
        AssertUtil.isTrue(StringUtils.isEmpty(addAdminDto.getAdminPassword()), "密码不能为空");
        AssertUtil.isTrue(StringUtils.isEmpty(addAdminDto.getAdminUsername()), "用户名不能为空");
        AssertUtil.isTrue(StringUtils.isEmpty(addAdminDto.getAdminPhone()), "手机号不能为空");
        AssertUtil.isTrue(PhoneUtils.isMobile(addAdminDto.getAdminPhone()) == false, "手机号格式错误");
        AdminBean adminBean = adminMapper.selectByAccount(addAdminDto.getAdminAccount());
        AssertUtil.isTrue(adminBean != null, "账号已存在");
        AdminBean insert = new AdminBean();
        insert.setAdminPassword(Md5Util.encode(addAdminDto.getAdminPassword()));
        insert.setAdminAccount(addAdminDto.getAdminAccount());
        insert.setAdminUsername(addAdminDto.getAdminUsername());
        insert.setAdminPhone(addAdminDto.getAdminPhone());
        insert.setAdminFace("http://localhost:8082/file/default_avatar.png");
        insert.setAdminStatus(1);
        insert.setAdminCreateTime(new Date());
        insert.setAdminUpdateTime(new Date());
        int result = adminMapper.insert(insert);

        return result == 1 ? 1 : 0;
    }

    /**
     * @description:禁用账户
     * @author: wyj
     * @date: 2024/4/16 21:49
     * @param:
     * @return:
     */
    @Override
    public Integer disableAdmin(Integer id) {
        //参数校验
        AssertUtil.isTrue(id == null || id == 0, "参数异常");
        AdminBean adminBean = adminMapper.selectById(id);
        AssertUtil.isTrue(adminBean == null, "管理员账户不存在");
        AssertUtil.isTrue(adminBean.getAdminStatus() == 0, "账户已被禁用");
        adminBean.setAdminStatus(0);
        int result = adminMapper.updateById(adminBean);
        return result == 1 ? 1 : 0;
    }

    /**
     * @description: 启用管理员账户
     * @author: wyj
     * @date: 2024/4/16 21:49
     * @param:
     * @return:
     */
    @Override
    public Integer enableAdmin(Integer id) {
        //参数校验
        AssertUtil.isTrue(id == null || id == 0, "参数异常");
        AdminBean adminBean = adminMapper.selectById(id);
        AssertUtil.isTrue(adminBean == null, "管理员账户不存在");
        AssertUtil.isTrue(adminBean.getAdminStatus() == 1, "账户已被启用");
        adminBean.setAdminStatus(1);
        int result = adminMapper.updateById(adminBean);
        return result == 1 ? 1 : 0;
    }

    private String saveImage(MultipartFile file) {
        String realPath = "E:/img";
        String fileName = UUID.randomUUID().toString().replace("-", "");
        // 整个URL   最后拼接file的后缀名
        String imgURL = "http://localhost:8082/file/" + fileName + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String filePath = realPath + "/" + fileName + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgURL;
    }

    private Boolean deleteImage(String avatarUrl) {
        String avatarURL = avatarUrl;
        String endURL = avatarURL.substring(avatarURL.lastIndexOf("/") + 1);
        String realPath = "E:/img";
        String filePath = realPath + "/" + endURL;
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        } else {
            return false;
        }
        return true;
    }


}
